import 'package:flutter/material.dart';
import 'package:flutter_hplus/components/tables/widgets/h_data_column.dart';

/// 数据表格控制器 - 用于管理表格状态和事件处理
class HDataTableController extends ChangeNotifier {
  // 排序相关
  bool _sortAscending = true;
  int? _sortColumnIndex;
  String? _sortField; // 添加排序字段
  
  // 分页相关
  int _currentPage = 1;
  int _rowsPerPage;
  int _totalPages = 1;
  
  // 搜索相关
  String _searchQuery = '';
  final TextEditingController searchController = TextEditingController();
  
  // 过滤后的数据
  List<Map<String, dynamic>> _filteredData = [];
  // 当前页显示的数据
  List<Map<String, dynamic>> _currentPageData = [];
  
  // 原始数据
  List<Map<String, dynamic>> _originalData = [];

  // 当前悬停的行索引
  int? _hoveredRowIndex;
  
  // 列宽状态 - 保存用户调整后的列宽
  List<double> _columnWidths = [];
  
  HDataTableController({
    required int defaultRowsPerPage,
    required List<Map<String, dynamic>> data,
    required int columnsCount,
  }) : _rowsPerPage = defaultRowsPerPage {
    _originalData = List.from(data);
    _filteredData = List.from(data);
    _columnWidths = List.filled(columnsCount, 0.0);
    _updateDisplayData();
  }
  
  // Getters
  bool get sortAscending => _sortAscending;
  int? get sortColumnIndex => _sortColumnIndex;
  int get currentPage => _currentPage;
  int get rowsPerPage => _rowsPerPage;
  int get totalPages => _totalPages;
  String get searchQuery => _searchQuery;
  List<Map<String, dynamic>> get filteredData => _filteredData;
  List<Map<String, dynamic>> get currentPageData => _currentPageData;
  int? get hoveredRowIndex => _hoveredRowIndex;
  List<double> get columnWidths => _columnWidths;
  
  // 更新数据源
  void updateData(List<Map<String, dynamic>> newData) {
    _originalData = List.from(newData);
    _updateDisplayData();
  }
  
  // 更新列数
  void updateColumnsCount(int count) {
    if (_columnWidths.length != count) {
      final oldWidths = List.from(_columnWidths);
      _columnWidths = List.filled(count, 0.0);
      
      // 保留已有的列宽设置
      for (int i = 0; i < oldWidths.length && i < count; i++) {
        _columnWidths[i] = oldWidths[i];
      }
      
      notifyListeners();
    }
  }
  
  /// 更新显示的数据
  void _updateDisplayData() {
    // 应用搜索过滤
    if (_searchQuery.isNotEmpty) {
      _filteredData = _originalData.where((row) {
        return row.values.any((value) => 
          value.toString().toLowerCase().contains(_searchQuery.toLowerCase()));
      }).toList();
    } else {
      _filteredData = List.from(_originalData);
    }
    
    // 应用排序
    if (_sortColumnIndex != null && _sortField != null) {
      _filteredData.sort((a, b) {
        final aValue = a[_sortField];
        final bValue = b[_sortField];
        
        if (aValue == null && bValue == null) return 0;
        if (aValue == null) return _sortAscending ? -1 : 1;
        if (bValue == null) return _sortAscending ? 1 : -1;
        
        int comparison;
        if (aValue is num && bValue is num) {
          comparison = aValue.compareTo(bValue);
        } else {
          comparison = aValue.toString().compareTo(bValue.toString());
        }
        
        return _sortAscending ? comparison : -comparison;
      });
    }
    
    // 计算总页数
    _totalPages = (_filteredData.length / _rowsPerPage).ceil();
    if (_totalPages == 0) _totalPages = 1;
    
    // 确保当前页在有效范围内
    if (_currentPage > _totalPages) {
      _currentPage = _totalPages;
    }
    
    // 获取当前页数据
    final startIndex = (_currentPage - 1) * _rowsPerPage;
    final endIndex = startIndex + _rowsPerPage > _filteredData.length 
        ? _filteredData.length 
        : startIndex + _rowsPerPage;
    
    if (startIndex < _filteredData.length) {
      _currentPageData = _filteredData.sublist(startIndex, endIndex);
    } else {
      _currentPageData = [];
    }
    
    notifyListeners();
  }
  
  /// 处理排序
  void handleSort(int columnIndex, String field) {
    if (_sortColumnIndex == columnIndex) {
      // 如果点击的是当前排序列，则切换排序方向
      _sortAscending = !_sortAscending;
    } else {
      // 如果点击的是新列，则设置为升序
      _sortColumnIndex = columnIndex;
      _sortField = field;
      _sortAscending = true;
    }
    
    _updateDisplayData();
  }
  
  /// 处理搜索
  void handleSearch(String query) {
    _searchQuery = query;
    _currentPage = 1; // 重置到第一页
    _updateDisplayData();
  }
  
  /// 处理页码变化
  void handlePageChange(int page) {
    _currentPage = page;
    _updateDisplayData();
  }
  
  /// 处理每页行数变化
  void handleRowsPerPageChange(int? value) {
    if (value != null) {
      _rowsPerPage = value;
      _currentPage = 1; // 重置到第一页
      _updateDisplayData();
    }
  }
  
  /// 设置悬停行
  void setHoveredRow(int? rowIndex) {
    if (_hoveredRowIndex != rowIndex) {
      _hoveredRowIndex = rowIndex;
      notifyListeners();
    }
  }
  
  /// 调整列宽
  void resizeColumn(int columnIndex, double width) {
    if (columnIndex >= 0 && columnIndex < _columnWidths.length) {
      _columnWidths[columnIndex] = width;
      notifyListeners();
    }
  }
  
  /// 重置列宽
  void resetColumnWidth(int columnIndex) {
    if (columnIndex >= 0 && columnIndex < _columnWidths.length) {
      _columnWidths[columnIndex] = 0.0;
      notifyListeners();
    }
  }
  
  /// 计算列宽
  void calculateColumnWidths(List<HDataColumn> columns, double totalWidth) {
    // 首先计算总flex和固定宽度
    double remainingFlex = 0;
    double usedWidth = 0;
    
    // 先处理已经手动调整宽度的列和固定宽度的列
    for (int i = 0; i < columns.length; i++) {
      final column = columns[i];
      
      // 优先使用手动调整的宽度
      if (_columnWidths[i] > 0) {
        // 已手动调整宽度的列占用固定宽度
        usedWidth += _columnWidths[i];
      } 
      // 其次使用设置的固定宽度
      else if (column.width != null) {
        _columnWidths[i] = column.width!;
        usedWidth += column.width!;
      }
      // 最后才使用flex
      else {
        // 未调整的列累加flex值
        remainingFlex += column.flex;
      }
    }
    
    // 计算剩余可用宽度
    double remainingWidth = totalWidth - usedWidth;
    
    // 然后根据flex比例分配剩余宽度给未调整的列
    for (int i = 0; i < columns.length; i++) {
      final column = columns[i];
      
      // 只处理未手动调整且未设置固定宽度的列
      if (_columnWidths[i] <= 0 && column.width == null) {
        double colWidth;
        
        // 如果是最后一列并且没有足够剩余flex，直接分配所有剩余宽度
        if (i == columns.length - 1 && remainingFlex == column.flex) {
          colWidth = remainingWidth;
        } else {
          // 按flex比例分配宽度
          colWidth = remainingWidth * (column.flex / remainingFlex);
        }
        
        // 应用最小/最大宽度限制
        if (column.minWidth != null && colWidth < column.minWidth!) {
          colWidth = column.minWidth!;
        }
        if (column.maxWidth != null && colWidth > column.maxWidth!) {
          colWidth = column.maxWidth!;
        }
        
        _columnWidths[i] = colWidth;
      }
    }
    
    notifyListeners();
  }
  
  @override
  void dispose() {
    searchController.dispose();
    super.dispose();
  }
} 